import com.baidu.aip.ocr.AipOcr;
import entity.custom.CustomImage;
import entity.custom.Image;
import manager.CreateQrCode;
import org.apache.commons.lang3.StringEscapeUtils;
import redis.JedisConnectPool;
import entity.menu.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import entity.template.*;
import util.Request;
import service.WxServiceImpl;
import util.XmlOrJson;

import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class test {
    static InputStream in= test.class.getClassLoader().getResourceAsStream("wx-config.xml");
    static Map<String,String> Xmlmap= WxServiceImpl.parseRequest(in);
    //微信
    private static final String APPID=Xmlmap.get("appid");
    private static final String SECRT=Xmlmap.get("secrt");
    private static final String GET_TOKEN_URL=Xmlmap.get("getToken");
    private static final String UPLOAD_URL=Xmlmap.get("uploadUrl");
    //百度接口
    private static final String APP_ID = Xmlmap.get("baiduID");
    private static final String API_KEY = Xmlmap.get("baiduKey");
    private static final String SECRET_KEY = Xmlmap.get("baiduSecret");
    //微信ai
    private static final String AI_APPID=Xmlmap.get("aiAppid");
    private static final String AI_TOKEN=Xmlmap.get("aiToken");
    private static final String AI_KEY=Xmlmap.get("aiKey");
    private static final String AI_SIGN_URL=Xmlmap.get("aiSignUrl");
    private static final String AI_BOT_URL=Xmlmap.get("aiBotUrl");
    private static final String SEND_URL=Xmlmap.get("sendTMUrl");
    private static final String GET_MEDIA=Xmlmap.get("getMedia");


    @Test
    public void testAI(){
        String url=AI_BOT_URL.replace("{TOKEN}",AI_TOKEN);
        Map<String,String> aiBotMap=new HashMap<>();
        aiBotMap.put("signature", WxServiceImpl.getSignature());
        aiBotMap.put("query","wef");
        String answer= Request.sendPost(url,aiBotMap);
        JSONObject jsonObject=new JSONObject(answer);
        System.out.println(jsonObject.getString("answer").getClass());
    }
    @Test
    public void testPic(){
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);


        // 调用接口
        String path = "C:\\Users\\15357\\Desktop\\2.png";
        JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
        JSONArray jsonArray=res.getJSONArray("words_result");
        Iterator<Object> iterator=jsonArray.iterator();
        StringBuilder sb=new StringBuilder();
//        while (iterator.hasNext()){
//            JSONObject jsonObject= (JSONObject) iterator.next();
//            sb.append(jsonObject.getString("words")+"\n");
//        }
//        System.out.println(sb);
        System.out.println(jsonArray);
    }

//    @Test
//    public void access(){
//        SqlSession sqlSession= MyBatisUtils.getSqlSession();
//        Access_token access_token=sqlSession.selectOne("mapper.accessMapper.selectAccess");
//        System.out.println(access_token);
//        sqlSession.close();
//    }
    @Test
    public void testToken(){
        InputStream in=getClass().getClassLoader().getResourceAsStream("wx-config.xml");
        Map<String,String> map= WxServiceImpl.parseRequest(in);
        String APPID=map.get("appid");
        String SECRT=map.get("secrt");
        String GET_TOKEN_URL=map.get("getToken");
        String url=GET_TOKEN_URL.replace("APPID",APPID).replace("APPSECRET",SECRT);
        String tokenstr= Request.get(url);
        System.out.println(tokenstr);

    }


    @Test
    public void testButton(){
        Button button=new Button();
        button.getButton().add(new ClickButton("点我","1"));
        button.getButton().add(new ViewButton("便民系统","golxen.cn"));
        SubButton sb=new SubButton("菜单");
        sb.getSub_button().add(new ClickButton("啥也不是","31"));
        sb.getSub_button().add(new ViewButton("百度一下","www.baidu.com"));
        sb.getSub_button().add(new PhotoOrAlbum("传图","33"));
        button.getButton().add(sb);
        JSONObject jsonObject=new JSONObject(button);
        System.out.println(jsonObject);
    }

    @Test
    public void testTM(){
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String url=SEND_URL.replace("ACCESS_TOKEN", WxServiceImpl.getAccessToken());
        First first=new First("测试");
        Keyword1 keyword1=new Keyword1("打卡失败");
        Keyword2 keyword2=new Keyword2(dateTime.format(formatter));
        Remark remark=new Remark("测试");
        WeishaoData weishaoData =new WeishaoData(first,keyword1,keyword2,remark);
        WeishaoTM weishaoTM=new WeishaoTM("oej9T6Bhr-35F3r2ksAtFKgfIjVk",
                "o9W4pSorKtHqcrHXkKFbV8FV7ICJZ3udFvER9owVfr8", weishaoData);
        JSONObject jsonObject=new JSONObject(weishaoTM);
        String result= Request.sendPost(url,jsonObject.toString());
        System.out.println(result);
//        System.out.println(jsonObject);
    }

    @Test
    public void testWeishao(){
        String json="{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
        String xml="<appid>wx16c534708bb583a3</appid>\n" +
                "    <appidTest>wx7df459d39e09d43c</appidTest>";
        StringBuilder str = new StringBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        String line=null;
        while (true) {
            try {
                if ((line = r.readLine()) == null) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            str.append(line);
        }
        System.out.println(str.toString());
        System.out.println(XmlOrJson.getType(str.toString()));

    }

    @Test
    public void testXml() throws Exception {
        InputStream in= WxServiceImpl.class.getClassLoader().getResourceAsStream("wx-config.xml");
        Map<String,String> Xmlmap= WxServiceImpl.parseRequest(in);
        System.out.println(Xmlmap);
    }
    @Test
    public void testUpload(){
        String path="C:\\Users\\Administrator\\Pictures\\img-wFO5Jx2iuBCPZYKtBWRgr2HQ.png";
        String url=UPLOAD_URL.replace("ACCESS_TOKEN",WxServiceImpl.getAccessToken())
                .replace("TYPE","image");
        String resp=Request.uploadPostLocal(url,path);
        System.out.println(resp);

//        String url=GET_MEDIA.replace("ACCESS_TOKEN", WxServiceImpl.getAccessToken())
//                .replace("MEDIA_ID","zd6dQFHEybYxiPQp2o5DayrlGdg_upV1Xaz1-W7weX70i05KbisiYrfeYHkZGNUr");
//        String resp= Request.get(url);
//        System.out.println(resp);

    }

    @Test
    public void testQrCode(){
        System.out.println(CreateQrCode.getCodeUrl());
    }

    @Test
    public void testGetUser(){
        System.out.println(WxServiceImpl.getUserInfo("oxHlE6JNtT2RfJw__PslJ4x9kuhg"));
    }

    @Test
    public void testRedis(){
        JedisConnectPool jedisPool=new JedisConnectPool();
//        jedisPool.setValue("test1","test1");
//        System.out.println(jedisPool.getValue("test1"));
    }

    @Test
    public void testERNIE(){
        String tokenStr= Request.sendPostERNIE("https://wenxin.baidu.com/moduleApi/portal/api/oauth/token?grant_type=client_credentials&client_id=XYxD2aH66jMa6wEjGA3akdaPiEy7rIMz&client_secret=7O4XF0Zs4pI3ZM7rZliQAiuFxh5vvE3v",null);
        JSONObject jsonObject=new JSONObject(tokenStr);
        String token=jsonObject.getString("data");
        System.out.println(token);
    }

    @Test
    public void testAPI(){
//        System.out.println(API.uploadPostUrl("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=61_W9bNywWQ80x-VX3FiVZ3XOh0PqhV6VokUL9MYEowkMCYf0xLfmxR13Hv8nE3_lIYIaJ4y8xZfhgg0hTvZMyWMUL8AqgAP0yQAfhJKKw6ly85F-o4lCPG3UBSKmd5md7HFIIBDDWR7G9FSOXSXXYfAJAFFG&type=image","https://wenxin.baidu.com/younger/file/ERNIE-ViLG/78107785ccaccdae53f151e8e4424e5dex"));

        Image image=new Image("ttt");
        CustomImage customImage=new CustomImage("tt",image);
        String sendData= com.alibaba.fastjson.JSON.toJSONString(customImage);
        System.out.println(sendData);

    }

    @Test
    public void testProxy() throws Exception{
        System.out.println(Request.request(
                "http://icanhazip.com/",
                null,null));
    }

    @Test
    public void testAI2() throws Exception{
        HashMap<String,Object> headerMap=new HashMap<>();
        headerMap.put("Content-Type","application/json");
        headerMap.put("Authorization","Bearer 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");
        String ask="你好";
        String data="{\"model\":\"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\",\"content\": \""+ ask +"\"}]}";
        Object response=Request.requestByProxy("https://api.openai.com/v1/chat/completions",headerMap,data);
        System.out.println(response);
    }

    @Test
    public void testAI3() throws Exception{
        HashMap<String,Object> headerMap=new HashMap<>();
        headerMap.put("Content-Type","application/json");
        headerMap.put("Authorization","Bearer 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");
        String ask="跑车";
        String data="{\"prompt\":\""+ ask +"\", \"n\": 1,\"size\":\"512x512\"}";
        Object response=Request.requestByProxy("https://api.openai.com/v1/images/generations",headerMap,data);
        System.out.println(response);
    }

    @Test
    public void testJson() throws Exception{
        String data="{\"model\":\"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\",\"content\": \"战争雷霆\"}, {\"role\": \"assistant\",\"content\": \"《战争雷霆》（War Thunder）是一款由俄罗斯游戏开发商Gaijin Entertainment开发并发布的免费在线多人战争游戏。游戏设定在二战及冷战时期，在游戏中玩家可以操控各国的战斗机、坦克、舰船等战争装备进行实时的战斗对战。\n" +
                "\n" +
                "《战争雷霆》提供了多个游戏模式，包括空战、地面战和海战。玩家可以自由选择加入不同的国家，如美国、苏联、德国、英国和日本等，并以此国家为基础解锁和升级各种战斗机和坦克。游戏中的战斗场景还包括了多种环境，如城市、农村和荒野，以及多种天气条件，如晴天、雨天和雪天等。\n" +
                "\n" +
                "在游戏中，玩家需要运用战略和战术技巧，与其他玩家进行实时对战。游戏中的各种装备和飞行器都有不同的性能和特点，需要玩家根据自己的游戏风格和策略选择合适的装备来组成自己的战斗队伍。同时，游戏还提供了丰富的升级和解锁系统，玩家可以通过战斗中获得的经验和资源来升级装备和解锁新的战斗机和坦克。\n" +
                "\n" +
                "《战争雷霆》以其逼真的画面和战斗体验受到了广大玩家的好评，并积极更新和拓展游戏内容，提供了更多的战斗模式和新的装备选择。游戏也定期举办各种比赛和活动，给予玩家更多的挑战和奖励。\"}, {\"role\": \"user\",\"content\": \"好的\"}]}";
        System.out.println(StringEscapeUtils.unescapeJson(data));
    }
}
